#include <QtCore/QCoreApplication>
#include <QStringList>
#include <QTextStream>
#include <QSqlDatabase>
#include <QTime>
#include <QDebug>

#include <iostream>
#include <exception>

#include "settings.h"
#include "db/dbconnection.h"
#include "udfimporter.h"
#include "consoleprogressobserver.h"
#include "udfexception.h"

void printHelp()
{
    using namespace std;
    cout << "Usage: \n";
    cout << "udfImporter -f udf_file_path -s db_server -db db_name -u db_user -p db_password\n";
}

void printSettings(Settings &settings)
{
    using namespace std;
    QTextStream cout(stdout, QIODevice::WriteOnly);

    cout << "File path: " << settings.getFilePath() << endl;
    cout << "Database server: " << settings.getDbServer() << endl;
    cout << "Database name: " <<  settings.getDbName() << endl;
    cout << "Database user: " << settings.getDbUser() << endl;
    cout << "Database password: " << settings.getDbPassword() << endl << endl;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    Settings settings;
    QStringList params = a.arguments();
    if(!settings.parseFromCommandLine(params))
    {
        printHelp();
        return 0;
    }

    printSettings(settings);

    QSharedPointer<DbConnection> dbConnection = DbConnection::instance();

    dbConnection->setupConnection(settings);

    try
    {
        UdfImporter importer;
        ConsoleProgressObserver observer;

        QTime time;
        time.start();

        QString filePath = settings.getFilePath();
        importer.importFromFile(filePath, &observer);
        std::cout << endl << endl;

        std::cout << "Import time: " << time.elapsed() << " msec" << endl;
        qDebug() << "Import time: " << time.elapsed() << " msec" << endl;
    }
    catch(UdfException exc)
    {
        QTextStream cout(stdout, QIODevice::WriteOnly);
        cout << exc.getMessage() << endl;
    }

    return 1;
}
